<template>
  <!-- 级联选择器 -->
  <div class="pho-form-item">
    <van-field
      :value="cascaderText"
      :label="showLabel ? $attrs.label : ''"
      :name="$attrs.__vModel__"
      :required="$attrs.required"
      :rules="$attrs.rules"
      :placeholder="$attrs.placeholder"
      input-align="right"
      :disabled="$attrs.disabled"
      :clearable="$attrs.clearable"
      :is-link="!isTop"
      readonly
      @click="onClick"
      @clear.stop
    />
    <van-popup v-model="show" round position="bottom">
      <van-cascader
        v-model="formValue"
        v-bind="$attrs"
        :field-names="fieldNames"
        @close="show = false"
        @finish="onConfirm"
      />
    </van-popup>
  </div>
</template>

<script>
import { getPathById } from "../../utils/index";
export default {
  name: "phone-form-cascader",
  model: {
    prop: "value", // 绑定的值，通过父组件传递
    event: "update",
  },
  props: {
    value: {
      default: "",
    },
    // 是否为上下布局
    isTop: {
      type: Boolean,
      default: false,
    },
    // 是否展示标题
    showLabel: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      formValue: "",
      show: false,
    };
  },
  computed: {
    // 自定义 options 结构中的字段	object	{ text: 'text', value: 'value', children: 'children' }
    fieldNames() {
      const props = this.$attrs.props.props;
      return {
        text: props.label || "text",
        value: props.value || "value",
        children: props.children || "children",
      };
    },
    // 选中后显示的文字
    cascaderText() {
      let text = "";
      if (this.formValue) {
        // 显示的文字
        const path = getPathById(
          this.$attrs.options,
          this.formValue,
          this.fieldNames
        ).map((it) => it[this.fieldNames.text]);
        // 间隔符
        const separator = this.$attrs.separator;
        // 是否展示全路径
        const showAllLevels = this.$attrs.showAllLevels;
        text = showAllLevels ? path.join(separator) : path[path.length - 1];
      }

      return text;
    },
  },
  watch: {
    value: {
      immediate: true,
      deep: true,
      handler(newValue) {
        this.formValue = "";
        if (newValue && newValue.length) {
          this.formValue = newValue[newValue.length - 1];
        }
      },
    },
  },

  methods: {
    onClick() {
      if (this.$attrs.disabled || this.$attrs.readonly) return;
      this.show = true;
    },
    onConfirm() {
      // 获取选中节点的全路径
      const path = getPathById(
        this.$attrs.options,
        this.formValue,
        this.fieldNames
      ).map((it) => it[this.fieldNames.value]);
      this.$emit("update", path);
      this.show = false;
    },
  },
};
</script>

<style lang="scss" scoped></style>
